﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Shell;

namespace LuyenThiVer03
{
    public partial class PageChuyenDe
    {
        private int MucKienThucID { get; set; }
        private int Socau { get; set; }
        private string Mon { get; set; }

        public PageChuyenDe()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var progress = new ProgressIndicator { IsVisible = true, Text = "Đang tải ...", IsIndeterminate = true };
            SystemTray.SetProgressIndicator(this, progress);
            Mon = NavigationContext.QueryString["mon"];
            var mucKienThuc = new MucKienThucWebService.MucKienThucWebServiceSoapClient();
            mucKienThuc.SelectAllByMonHoc_IDCompleted += MucKienThuc_OnSelectAllByMonHoc_IDCompleted;
            mucKienThuc.SelectAllByMonHoc_IDAsync(Mon);          
        }

        private void MucKienThuc_OnSelectAllByMonHoc_IDCompleted(object sender, MucKienThucWebService.SelectAllByMonHoc_IDCompletedEventArgs e)
        {            
            var listMucKienThuc = new List<MucKienThucWebService.MucKienThucEntity>(e.Result);
            ListMucKT.ItemsSource = listMucKienThuc;
            SystemTray.GetProgressIndicator(this).IsVisible = false;
        }

        private void ListMucKT_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var mucKienThuc = (MucKienThucWebService.MucKienThucEntity)e.AddedItems[0];
                MucKienThucID = mucKienThuc.MucKienThuc_ID;
                LoadCauHoiByMucKienThuc(MucKienThucID);  
            }
            catch (Exception)
            {
                ListMucKT.SelectionChanged += ListMucKT_OnSelectionChanged;
            }                                  
        }

        private void LoadCauHoiByMucKienThuc(int mucKienThucID)
        {
            var goiCauHoi = new GoiCauHoiWebService.GoiCauHoiWebServiceSoapClient();
            goiCauHoi.SelectAllByMucKienThuc_IDCompleted += GoiCauHoi_OnSelectAllByMucKienThuc_IDCompleted;
            goiCauHoi.SelectAllByMucKienThuc_IDAsync(mucKienThucID);
        }

        private void GoiCauHoi_OnSelectAllByMucKienThuc_IDCompleted(object sender, GoiCauHoiWebService.SelectAllByMucKienThuc_IDCompletedEventArgs e)
        {
            var listCauHoi = new List<GoiCauHoiWebService.GoiCauHoiEntity>(e.Result);
            Socau = listCauHoi.Count;
            NavigationService.Navigate(new Uri("/PageSoCauOnThi.xaml?MucKienThucID=" + MucKienThucID + "&SoCau=" + Socau + "&mon=" + Mon, UriKind.Relative));
        }
    }
}